package testdb.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import testdb.models.User;
import testdb.models.UserDao;

@Controller
public class UserController{

@RequestMapping("/create")
@ResponseBody
public String create(long id,String firstname,String lastname){
User user=new User(id,firstname,lastname);
userDao.save(user);
return "user created!";
}

@RequestMapping("/delete")
@ResponseBody
public String delete(long id){
try{
User user=new User(id);
userDao.delete(user);
}
catch(Exception ex){
return "Error deleting the user: "+ex.toString();
}
return "User successfully deleted!";
}

  /**
   * GET /get-by-email  --> Return the id for the user having the passed
   * email.
   */
  @RequestMapping("/firstname")
  @ResponseBody
  public String getByfirstname(String firstname) {
    String userId = "";
    try {
      User user = userDao.findByfirstname(firstname);
      userId = String.valueOf(user.getId());
    }
    catch (Exception ex) {
      return "User not found";
    }
    return "The user id is: " + userId;
  }
  
  /**
   * GET /update  --> Update the email and the name for the user in the 
   * database having the passed id.
	 * @param id
	 * @param firstname
	 * @param lastname
   */
  @RequestMapping("/update")
  @ResponseBody
  public String updateUser(long id, String firstname, String lastname) {
    try {
      User user = userDao.findOne(id);
      user.setfirstname(firstname);
      user.setlastname(lastname);
      userDao.save(user);
    }
    catch (Exception ex) {
      return "Error updating the user: " + ex.toString();
    }
    return "User succesfully updated!";
  }

  // Private fields

  @Autowired
  private UserDao userDao;
  
}
